package com.lz.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.gmall.common.execption.GmallException;
import com.lz.gmall.common.result.ResultCodeEnum;
import com.lz.gmall.product.entity.BaseTrademark;
import com.lz.gmall.product.entity.SkuInfo;
import com.lz.gmall.product.entity.SpuInfo;
import com.lz.gmall.product.service.BaseTrademarkService;
import com.lz.gmall.product.mapper.BaseTrademarkMapper;
import com.lz.gmall.product.service.SkuInfoService;
import com.lz.gmall.product.service.SpuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class BaseTrademarkServiceImpl extends ServiceImpl<BaseTrademarkMapper, BaseTrademark>
    implements BaseTrademarkService{

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SpuInfoService spuInfoService;

    /**
     * 分页获取所有品牌
     * @param pageNum 页码
     * @param limit 每页条数
     * @return 分页对象
     */
    @Override
    public Page<BaseTrademark> getBaseTrademarkByPage(Integer pageNum, Integer limit) {
        Page<BaseTrademark> page = new Page<>(pageNum, limit);
        this.page(page);
        return page;
    }

    /**
     * 添加品牌
     * @param baseTrademark 添加品牌信息
     */
    @Override
    public void saveBaseTrademark(BaseTrademark baseTrademark) {
        this.save(baseTrademark);
    }

    /**
     * 修改品牌
     * @param baseTrademark 修改品牌信息
     */
    @Override
    public void updateBaseTrademark(BaseTrademark baseTrademark) {
        this.updateById(baseTrademark);
    }

    /**
     * 判断品牌是否关联spu，sku
     * @param tmId 品牌id
     */
    @Override
    public void deleteBaseTrademarkById(Long tmId) {

        LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skuInfoLambdaQueryWrapper.eq(SkuInfo::getTmId,tmId);
        List<SkuInfo> skuInfoList = skuInfoService.list(skuInfoLambdaQueryWrapper);
        if (skuInfoList!=null && skuInfoList.size()>0){
            //品牌关联了stu，不允许删除
            throw new GmallException(ResultCodeEnum.REF_SKU_ERROR);
        }

        LambdaQueryWrapper<SpuInfo> spuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuInfoLambdaQueryWrapper.eq(SpuInfo::getTmId,tmId);
        List<SpuInfo> spuInfoList = spuInfoService.list(spuInfoLambdaQueryWrapper);
        if (spuInfoList!=null && spuInfoList.size()>0){
            //品牌关联了spu，不允许删除
            throw new GmallException(ResultCodeEnum.REF_SPU_ERROR);
        }

        //没有关联，可以删除
        this.removeById(tmId);

    }
}




